package com.qifei.xmlg_backend.utils.minio;

import com.sun.jdi.event.ExceptionEvent;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.SetBucketPolicyArgs;
import jakarta.validation.constraints.Min;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.nio.charset.StandardCharsets;

@Configuration
@RequiredArgsConstructor
@Slf4j
public class MinioClientProvider {

    private final MinioProps minioProps;


    @Bean
    public MinioClient minioClient(){

        String bucketName = minioProps.getBucketName();
        MinioClient client = MinioClient.builder().endpoint(minioProps.getEndpoint())
                .credentials(minioProps.getAccessKey(), minioProps.getSecretKey())
                .build();
        try{
            // 判断桶是否存在
            boolean exists = client.bucketExists(
                    BucketExistsArgs.builder().bucket(bucketName).build()
            );

            if (!exists){
                log.info("MinIO bucket 不存在，正在创建：{}",bucketName );
                client.makeBucket(
                        MakeBucketArgs.builder().bucket(bucketName).build()
                );
                log.info("MinIO bucket 创建成功：{}",bucketName);
            }else{
                log.info("MinIO bucket 已经存在：{}", bucketName);
            }

            // 设置桶的权限 让图片可以直接访问
            String policyTemplate = new String(
                    this.getClass().getResourceAsStream("/config/policy.json").readAllBytes(),
                    StandardCharsets.UTF_8
            );
            String policyJson = String.format(policyTemplate, bucketName);
            // 设置权限
            client.setBucketPolicy(SetBucketPolicyArgs.builder()
                    .bucket(bucketName)
                    .config(policyJson)
                    .build());


        }catch (Exception e){
            log.error("❌ MinIO 连接失败或桶校验失败，程序终止！", e);
            throw new RuntimeException("MinIO 连接失败或桶创建失败: " + e.getMessage(), e);
        }
        return client;
    }
}
